package com.waypolice.common.pdfUtil;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author wangrang
 * @create 2018-04-20 10:27
 * @file name   PdfPageHelper
 * @desc 页码内部类
 **/
public class PdfPageHelper extends PdfPageEventHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(PdfPageHelper.class);

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try{
            PdfContentByte headAndFootPdfContent = writer.getDirectContent();
            headAndFootPdfContent.saveState();
            headAndFootPdfContent.beginText();
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            headAndFootPdfContent.setFontAndSize(bfChinese, 10);

            //文档页脚信息设置
            float y = document.bottom(-20);

            //页脚信息中间
            headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER,
                    "第"+writer.getPageNumber()+ "页",
            (document.right() + document.left())/2,
                    y, 0);

            headAndFootPdfContent.endText();
            headAndFootPdfContent.restoreState();
        }catch(DocumentException de) {
            LOGGER.error("创建pdf文件写入模板document异常"+de);
            de.printStackTrace();
        }catch(IOException de) {
            LOGGER.error("pdf添加页码读写pdf时IO读写异常"+de);
            de.printStackTrace();
        }
    }

}
